Skip to content

Python: Emit token usage with streaming chat completion agent. #12416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 9, 2025

Conversation

moonbox3
Copy link
Contributor

@moonbox3 moonbox3 commented Jun 9, 2025

Motivation and Context

The chat completion agent was not emitting token using during streaming invocation because we were only allowing through response.items. In the case of token usage, response.items is [] and the usage is contained as part of the message's metadata dict. This PR fixes that bug and allows for response.items or response.metadata.get("usage"). Two new samples are added to the concepts/agents/chat_completion dir to show how one can track token use for streaming and non-streaming agent invocation. Token usage handling is also added to the chat completion agent integration tests.

Description

Contribution Checklist

@moonbox3 moonbox3 self-assigned this Jun 9, 2025
@moonbox3 moonbox3 requested a review from a team as a code owner June 9, 2025 04:14
@moonbox3 moonbox3 added python Pull requests for the Python Semantic Kernel agents labels Jun 9, 2025
@markwallace-microsoft
Copy link
Member

markwallace-microsoft commented Jun 9, 2025

Python Test Coverage

Python Test Coverage Report •
FileStmtsMissCoverMissing
agents/chat_completion
   chat_completion_agent.py2242887%68, 73, 78, 84, 100, 102, 108–112, 170, 173, 183, 191, 194, 196, 205, 231, 250, 252–253, 255–256, 258, 406, 503, 580
connectors/ai
   completion_usage.py23865%21, 39–45
TOTAL27125462782% 

Python Unit Test Overview

Tests Skipped Failures Errors Time
3626 22 💤 0 ❌ 0 🔥 2m 2s ⏱️

@moonbox3 moonbox3 added this pull request to the merge queue Jun 9, 2025
Merged via the queue into microsoft:main with commit 4b23389 Jun 9, 2025
28 checks passed
@moonbox3 moonbox3 deleted the chat-complete-agent-stream-usage branch June 9, 2025 23:19
@github-project-automation github-project-automation bot moved this to Sprint: Done in Semantic Kernel Jun 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
agents documentation python Pull requests for the Python Semantic Kernel
Projects
Status: Sprint: Done
Development

Successfully merging this pull request may close these issues.

Python: Bug: invoke_stream method in chat_completion_agent.py not returning token usage data
4 participants